import 'dart:developer' as developer;

/// 年龄计算工具类 - 参考MyApplication2的CommunalMethodUtil.showUserAge()实现
class AgeCalculator {
  /// 根据生日计算准确年龄（完全参考MyApplication2的逻辑）
  /// 
  /// 对应MyApplication2中的：
  /// ```java
  /// public static int showUserAge(String birthday) {
  ///     int birthYear = Integer.parseInt(getYearFromDate(birthday));
  ///     int birthMonth = Integer.parseInt(getMonthFromDate(birthday)) - 1;
  ///     int birthDay = Integer.parseInt(getDayFromDate(birthday));
  ///     
  ///     Calendar today = Calendar.getInstance();
  ///     Calendar birthDate = Calendar.getInstance();
  ///     birthDate.set(birthYear, birthMonth, birthDay);
  ///     
  ///     int age = today.get(Calendar.YEAR) - birthDate.get(Calendar.YEAR);
  ///     
  ///     if (today.get(Calendar.DAY_OF_YEAR) < birthDate.get(Calendar.DAY_OF_YEAR)) {
  ///         age--; // 生日未过，年龄减1
  ///     }
  ///     return Math.max(age, 0);
  /// }
  /// ```
  static int calculateAge(String? birthday) {
    if (birthday == null || birthday.isEmpty) {
      developer.log('⚠️ 生日为空，返回年龄0');
      return 0;
    }
    
    try {
      developer.log('🎂 开始计算年龄，生日: $birthday');
      
      // 解析生日字符串 (格式: "1990-05-15" 或 "1990-5-15")
      final parts = birthday.split('-');
      if (parts.length != 3) {
        developer.log('❌ 生日格式错误: $birthday');
        return 0;
      }
      
      final birthYear = int.parse(parts[0]);
      final birthMonth = int.parse(parts[1]);
      final birthDay = int.parse(parts[2]);
      
      developer.log('📅 解析生日: $birthYear年$birthMonth月$birthDay日');
      
      final today = DateTime.now();
      final birthDate = DateTime(birthYear, birthMonth, birthDay);
      
      int age = today.year - birthDate.year;
      
      // 🔥 关键逻辑：检查今年的生日是否已过（参考MyApplication2的DAY_OF_YEAR比较）
      final todayDayOfYear = today.difference(DateTime(today.year)).inDays + 1;
      final birthDayOfYear = birthDate.difference(DateTime(birthDate.year)).inDays + 1;
      
      if (todayDayOfYear < birthDayOfYear) {
        age--; // 生日未过，年龄减1
        developer.log('🎈 今年生日未过，年龄减1');
      }
      
      final finalAge = age >= 0 ? age : 0; // 处理未来日期
      developer.log('✅ 计算完成，最终年龄: $finalAge岁');
      
      return finalAge;
    } catch (e) {
      developer.log('💥 年龄计算异常: $e');
      return 0;
    }
  }
  
  /// 格式化年龄显示
  static String formatAge(String? birthday) {
    final age = calculateAge(birthday);
    return age > 0 ? '${age}岁' : '0岁';
  }
  
  /// 获取年份（参考MyApplication2的getYearFromDate）
  static String getYearFromDate(String? date) {
    if (date == null || date.isEmpty) return '';
    
    final parts = date.split('-');
    if (parts.length >= 3) {
      return parts[0];
    }
    return '';
  }
  
  /// 获取月份（参考MyApplication2的getMonthFromDate）
  static String getMonthFromDate(String? date) {
    if (date == null || date.isEmpty) return '';
    
    final parts = date.split('-');
    if (parts.length >= 3) {
      return parts[1];
    }
    return '';
  }
  
  /// 获取日期（参考MyApplication2的getDayFromDate）
  static String getDayFromDate(String? date) {
    if (date == null || date.isEmpty) return '';
    
    final parts = date.split('-');
    if (parts.length >= 3) {
      return parts[2];
    }
    return '';
  }
  
  /// 验证生日格式是否正确
  static bool isValidBirthday(String? birthday) {
    if (birthday == null || birthday.isEmpty) return false;
    
    try {
      final parts = birthday.split('-');
      if (parts.length != 3) return false;
      
      final year = int.parse(parts[0]);
      final month = int.parse(parts[1]);
      final day = int.parse(parts[2]);
      
      // 基本范围检查
      if (year < 1900 || year > DateTime.now().year) return false;
      if (month < 1 || month > 12) return false;
      if (day < 1 || day > 31) return false;
      
      // 尝试创建DateTime验证日期有效性
      DateTime(year, month, day);
      return true;
    } catch (e) {
      return false;
    }
  }
}
